<?php

namespace App\Http\Controllers\Wechat;

use EasyWechat\Foundation\Application;
use App\Http\Controllers\Controller;
use App\Http\Requests;
use Log;
use App\keyword;
class IndexController extends Controller
{

    public function index(){
        echo 'hello world';exit;
    }

    /**
     * 处理微信的请求消息
     *
     * @return string
     */
    public function serve()
    {
        Log::info('request arrived.'); # 注意：Log 为 Laravel 组件，所以它记的日志去 Laravel 日志看，而不是 EasyWeChat 日志

        $wechat = app('wechat');
        $wechat->server->setMessageHandler(function($message){
            switch ($message->MsgType) {
                case 'event':$this->text($message->Content);
                    break;
                case 'text':
                    # 文字消息...
                    break;
                case 'image':
                    # 图片消息...
                    break;
                case 'voice':
                    # 语音消息...
                    break;
                case 'video':
                    # 视频消息...
                    break;
                case 'location':
                    # 坐标消息...
                    break;
                case 'link':
                    # 链接消息...
                    break;
                default:
                      return "欢迎关注 overtrue！";
                    break;
            }
        });

        Log::info('return response.');

        return $wechat->server->serve();
    }
/*
 * 回复文本消息
 * $keysord 用户请求的关键字
 */
    public function text($keyword){
        $data= keyword::where('keyword','like',"%$keyword%")->get();
        if(!empty($data)){
            return $data->content;
        }else{
            return '欢迎关注！';
        }
    }
    /**
     * 生成菜单
     */
    public function setMenu()
    {
        $wechat = app('wechat');

        $buttons = [
            [
                "type" => "click",
                "name" => "今日歌曲",
                "key"  => "V1001_TODAY_MUSIC"
            ],
            [
                "name"       => "菜单",
                "sub_button" => [
                    [
                        "type" => "view",
                        "name" => "搜索",
                        "url"  => "http://www.soso.com/"
                    ],
                    [
                        "type" => "view",
                        "name" => "视频",
                        "url"  => "http://v.qq.com/"
                    ],
                    [
                        "type" => "click",
                        "name" => "赞一下我们",
                        "key" => "V1001_GOOD"
                    ],
                ],
            ],
        ];

        $result = $wechat->menu->add($buttons);
        dump($result);
    }
}
